﻿
using RXY_Mall.Core;
using RXY_Mall.Core.Tool;
using RXY_Mall.Domain;
using RXY_Mall.Services;
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;

namespace RXY_Mall.AdminApi.Common
{
    public class SignExtension
    {
        /// <summary>
        /// 获得ManagerToken
        /// </summary>
        /// <param name="userid">用户ID</param>
        /// <returns></returns>
        public static ResponseService<ManagerToken> GetToken(int userid)
        {
            ResponseService<ManagerToken> resultMsg = null;

            //插入缓存
            ManagerToken token = (ManagerToken)HttpRuntime.Cache.Get(userid.ToString());
            if (HttpRuntime.Cache.Get(userid.ToString()) == null)
            {
                token = new ManagerToken();
                token.manager_id = userid;
                token.sign_token = Guid.NewGuid().ToString();
                token.expire_time = DateTime.Now.AddDays(1);
                HttpRuntime.Cache.Insert(token.manager_id.ToString(), token, null, token.expire_time, TimeSpan.Zero);
            }

            //返回token信息
            resultMsg = new ResponseService<ManagerToken>();
            resultMsg.code = 1;// (int)StatusCodeEnum.SUCCESS;
            resultMsg.msg = "";
            resultMsg.data = token;

            return resultMsg;
        }

        /// <summary>
        /// 设置ManagerToken
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="strtoken"></param>
        public static void SetToken(int userid, string strtoken)
        {
            //插入缓存
            if (HttpRuntime.Cache.Get(userid.ToString()) != null)
            {
                HttpRuntime.Cache.Remove(userid.ToString());
            }

            ManagerToken token = new ManagerToken();
            token.manager_id = userid;
            token.sign_token = strtoken;
            token.expire_time = DateTime.Now.AddDays(1);

            HttpRuntime.Cache.Insert(token.manager_id.ToString(), token, null, token.expire_time, TimeSpan.Zero);
        }

        /// <summary>
        /// 移除ManagerToken
        /// </summary>
        /// <param name="userid"></param>
        public static void RemoveToken(int userid)
        {
            //移除token
            if (HttpRuntime.Cache.Get(userid.ToString()) != null)
            {
                HttpRuntime.Cache.Remove(userid.ToString());
                SessionHelper.Remove("qujia");
            }
        }

        /// <summary>
        /// 校验签名
        /// </summary>
        /// <param name="timestamp">时间戳</param>
        /// <param name="nonce">随机数</param>
        /// <param name="userId">用户ID</param>
        /// <param name="version">版本号</param>
        /// <param name="signtoken">签名</param>
        /// <param name="data">数据</param>
        /// <returns></returns>
        private static string GetSign(string timestamp, string nonce, int userId, string version, string signtoken, string data)
        {
            //0.原始数据
            LogHelper.WriteLog(string.Format("timestamp:{0},nonce:{1},userId:{2},version:{3},signtoken:{4},data:{5}", timestamp, nonce, userId, version, signtoken, data));

            //1.去掉特殊字符
            string strData = data.Replace("\n", "").Replace("\r", "").Replace("\t", "").Replace(" ", "");
            LogHelper.WriteLog(string.Format("strData:{0}", strData));
            var guid = "056ba892-f785-4387-a701-d0c5851d29db";

            //2.拼接签名数据
            var signStr = timestamp + nonce + userId + version + signtoken + strData + guid;

            //将字符串中字符按升序排序 object-c排序不同 删除
            //var sortStr = string.Concat(signStr.OrderBy(c => c));
            LogHelper.WriteLog(string.Format("signStr:{0}", signStr));
            //3.MD5加密
            var md5 = CommonHelper.GetMD5(signStr);
            LogHelper.WriteLog(string.Format("md5:{0}", md5));

            //4.转化成大写
            string sign = md5.ToString().ToUpper();
            LogHelper.WriteLog(string.Format("sign:{0}", sign));
            return sign;
        }

        /// <summary>
        /// 验证签名
        /// </summary>
        /// <param name="timestamp">时间戳</param>
        /// <param name="nonce">随机数</param>        
        /// <param name="userid">用户ID</param>
        /// <param name="version">版本号</param>
        /// <param name="signtoken">ManagerToken</param>
        /// <param name="data">数据</param>
        /// <param name="signature">签名</param>
        /// <returns></returns>
        public static bool ValidateSign(string timestamp, string nonce, int userid, string version, string signtoken, string data, string signature)
        {
            if (signature.Equals(GetSign(timestamp, nonce, userid, version, signtoken, data))) return true;
            return false;
        }
    }

    public static class DistinctByClass
    {
        public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
        {
            HashSet<TKey> seenKeys = new HashSet<TKey>();
            foreach (TSource element in source)
            {
                if (seenKeys.Add(keySelector(element)))
                {
                    yield return element;
                }
            }
        }
    }

}